import dayjs from 'dayjs'
import Big from 'big.js'

/**
 * 通用工具方法集合
 */

// Token相关操作
export const TokenUtil = {
  key: 'access_token',
  // 设置token
  setToken(token) {
    localStorage.setItem(this.key, token)
  },
  // 获取token
  getToken() {
    return localStorage.getItem(this.key)
  },
  // 删除token
  removeToken() {
    localStorage.removeItem(this.key)
  },
  // 检查是否有token
  hasToken() {
    return !!this.getToken()
  }
}

// Storage操作封装
export const StorageUtil = {
  // localStorage操作
  local: {
    set(key, value) {
      if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      localStorage.setItem(key, value)
    },
    get(key) {
      let value = localStorage.getItem(key)
      try {
        return JSON.parse(value)
      } catch (e) {
        return value
      }
    },
    remove(key) {
      localStorage.removeItem(key)
    },
    clear() {
      localStorage.clear()
    }
  },
  
  // sessionStorage操作
  session: {
    set(key, value) {
      if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      sessionStorage.setItem(key, value)
    },
    get(key) {
      let value = sessionStorage.getItem(key)
      try {
        return JSON.parse(value)
      } catch (e) {
        return value
      }
    },
    remove(key) {
      sessionStorage.removeItem(key)
    },
    clear() {
      sessionStorage.clear()
    }
  }
}

// 日期时间格式化 - 使用 dayjs 重写
export const DateUtil = {
  format(date, fmt = 'YYYY-MM-DD HH:mm:ss') {
    return dayjs(date).format(fmt)
  },
  // 添加更多实用的日期处理方法
  add(date, number, unit) {
    return dayjs(date).add(number, unit)
  },
  subtract(date, number, unit) {
    return dayjs(date).subtract(number, unit)
  },
  isBefore(date1, date2) {
    return dayjs(date1).isBefore(date2)
  },
  isAfter(date1, date2) {
    return dayjs(date1).isAfter(date2)
  },
  isSame(date1, date2, unit = 'day') {
    return dayjs(date1).isSame(date2, unit)
  }
}

// URL参数操作
export const UrlUtil = {
  // 获取URL参数
  getQueryParam(name) {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    const r = window.location.search.substr(1).match(reg)
    if (r != null) return decodeURIComponent(r[2])
    return null
  },
  
  // 构建URL参数
  buildQuery(data) {
    let ret = []
    for (let key in data) {
      ret.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
    }
    return ret.join('&')
  }
}

// 数据类型检查
export const TypeUtil = {
  isString(o) { return typeof o === 'string' },
  isNumber(o) { return typeof o === 'number' },
  isBoolean(o) { return typeof o === 'boolean' },
  isFunction(o) { return typeof o === 'function' },
  isObject(o) { return Object.prototype.toString.call(o) === '[object Object]' },
  isArray(o) { return Array.isArray(o) },
  isNull(o) { return o === null },
  isUndefined(o) { return o === undefined },
  isEmpty(o) { return o === '' || o === null || o === undefined }
}

// 防抖函数
export const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

// 节流函数
export const throttle = (fn, delay) => {
  let last = 0
  return function (...args) {
    const now = Date.now()
    if (now - last > delay) {
      last = now
      fn.apply(this, args)
    }
  }
}

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null) return null
  if (typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj)
  if (obj instanceof RegExp) return new RegExp(obj)
  
  let newObj = Array.isArray(obj) ? [] : {}
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = deepClone(obj[key])
    }
  }
  return newObj
}

// 数字格式化
export const NumberUtil = {
  // 千分位格式化
  formatThousands(num) {
    return new Big(num || 0).toFormat()
  },
  
  // 保留小数位
  round(num, decimal = 2) {
    return new Big(num).round(decimal).toString()
  },
  
  // 添加更多数字计算方法
  add(a, b) {
    return new Big(a).plus(b).toString()
  },
  
  subtract(a, b) {
    return new Big(a).minus(b).toString()
  },
  
  multiply(a, b) {
    return new Big(a).times(b).toString()
  },
  
  divide(a, b) {
    return new Big(a).div(b).toString()
  }
}

// 随机字符串生成
export const randomString = (length = 32) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let str = ''
  for (let i = 0; i < length; i++) {
    str += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return str
} 


export const validatePassword = (rule, value, callback) => {
  // 密码长度8-15位
  if (value.length < 8 || value.length > 15) {
    callback(new Error('密码长度应在8到15个字符之间'));
    return;
  }

  // 检查密码复杂度
  const hasNumber = /\d/.test(value);
  const hasLetter = /[a-zA-Z]/.test(value);
  const hasSpecial = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);

  // 计算满足的条件数
  const conditions = [hasNumber, hasLetter, hasSpecial].filter(Boolean).length;

  if (conditions < 2) {
    callback(new Error('密码必须包含数字、字母和特殊字符中的至少两种'));
  } else {
    callback();
  }
};